import styles from "./index.module.less";
import { Title } from "../title/index.jsx";
import { Form, Input, Modal, Selector, Toast } from "antd-mobile";
import {
  idCardRegexp,
  insureTargetList,
  insureTargetValue,
  medicalInsuranceList,
  phoneRegexp,
} from "@/contstants.js";
import { QuestionCircleOutline } from "antd-mobile-icons";
import { CountdownTimer } from "@/components/countdown-timer/index.jsx";
import { Card } from "@/pages/insure/components/card/index.jsx";
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { useUserInfoStore } from "@/store/useUserStore.js";

export const ApplyForm = forwardRef(({ onSubmitVisibleChange }, ref) => {
  const submitRef = useRef(null);
  const formRef = useRef(null);
  const [target, setTarget] = useState(insureTargetValue.SELF);
  const userInfoStore = useUserInfoStore();

  useImperativeHandle(ref, () => {
    return {
      submit: () => {
        window.scrollTo(0, 0);
        formRef.current.submit();
      },
    };
  });

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          onSubmitVisibleChange(entry.isIntersecting);
        });
      },
      { rootMargin: "0px", threshold: 0 },
    );
    observer.observe(submitRef.current);

    return () => observer.unobserve(submitRef.current);
  }, []);
  const showMedicalInsuranceHelp = () => {
    const modal = Modal.show({
      title: "有无医保？",
      content:
        "指被保险人是否已参加社会医疗保险，包含:城镇职工基本医疗保险/城镇居民基本医疗保险/新型农村合作医疗(新农合)/城乡居民基本医疗",
      className: "medical-insurance-help",
      actions: [
        {
          key: "confirm",
          text: "我知道了",
          onClick: () => modal.close(),
        },
      ],
    });
  };

  const phoneRules = [
    { required: true },
    { pattern: phoneRegexp, message: "手机号格式错误" },
  ];

  const idCardRules = [
    { required: true },
    { pattern: idCardRegexp, message: "身份证号格式错误" },
  ];

  const handleSubmit = (values) => {
    Toast.show({
      content: `${JSON.stringify(values)}`,
      duration: 1000,
      afterClose: () => {},
    });
  };

  const handleFailed = ({ errorFields }) => {
    Toast.show(errorFields[0].errors[0]);
  };

  const isSelf = target === insureTargetValue.SELF;

  useEffect(() => {
    if (isSelf) {
      formRef.current.setFieldsValue({
        targetName: userInfoStore.name,
        targetIdCard: userInfoStore.idCard,
        targetPhone: userInfoStore.phone,
        selfName: "",
        selfIdCard: "",
        selfPhone: "",
      });
    } else {
      formRef.current.setFieldsValue({
        targetName: "",
        targetIdCard: "",
        targetPhone: "",
        selfName: userInfoStore.name,
        selfIdCard: userInfoStore.idCard,
        selfPhone: userInfoStore.phone,
      });
    }
  }, [isSelf]);

  return (
    <Card className={styles.container}>
      <div className={styles.estimate}>
        预估每月
        <span className={styles.money}>0.6</span>
        <span className={styles.unit}>元</span>
      </div>
      <div className={styles.tips}>
        （保费与年龄和有无社保相关，此保费以35岁为例详见费率表）
      </div>
      <Form
        className={"insure-apply-form"}
        layout="horizontal"
        onFinish={handleSubmit}
        onFinishFailed={handleFailed}
        ref={formRef}
        hasFeedback={false}
        initialValues={{ hasMedicalInsurance: [1] }}
      >
        <Title className={"group-title"}>为谁投保</Title>
        <Selector
          options={insureTargetList}
          columns={4}
          value={[target]}
          onChange={(values) => {
            setTarget(values.length ? values[0] : insureTargetValue.SELF);
          }}
        />
        <Form.Item
          label={"姓名"}
          name={"targetName"}
          rules={[{ required: true }]}
        >
          <Input placeholder={"信息严格保密，仅用于投保"} />
        </Form.Item>
        <Form.Item label={"身份证号"} name={"targetIdCard"} rules={idCardRules}>
          <Input placeholder={"信息严格保密，仅用于投保"} />
        </Form.Item>
        {isSelf && (
          <Form.Item label={"手机号码"} name={"targetPhone"} rules={phoneRules}>
            <Input placeholder={"您的信息将被严格保密"} />
          </Form.Item>
        )}
        <Form.Item
          label={
            <>
              有无医保{" "}
              <QuestionCircleOutline
                className={"question"}
                onClick={showMedicalInsuranceHelp}
              />
            </>
          }
          name={"hasMedicalInsurance"}
          rules={[{ required: true, message: "请选择有无医保" }]}
        >
          <Selector
            columns={2}
            options={medicalInsuranceList}
            className={"small"}
          />
        </Form.Item>
        {!isSelf && (
          <>
            <Title className={"group-title"}>本人信息(投保人)</Title>
            <Form.Item
              label={"姓名"}
              name={"selfName"}
              rules={[{ required: true }]}
            >
              <Input placeholder={"您的信息将被严格保密"} />
            </Form.Item>
            <Form.Item
              label={"身份证号"}
              name={"selfIdCard"}
              rules={idCardRules}
            >
              <Input placeholder={"您的信息将被严格保密"} />
            </Form.Item>
            <Form.Item label={"手机号码"} name={"selfPhone"} rules={phoneRules}>
              <Input placeholder={"您的信息将被严格保密"} />
            </Form.Item>
          </>
        )}
      </Form>
      <div
        className={styles.submit}
        ref={submitRef}
        onClick={() => formRef.current.submit()}
      >
        <div className={"hand"}></div>
      </div>
      <CountdownTimer timestamp={1716137481015} />
      <div className={styles.joinCount}>
        <i></i>
        已有 <span>5,352</span> 人加入保障
      </div>
    </Card>
  );
});
